package com.sunq.studio.utils;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

/**
 * Created by sunq on 2019/7/25.
 */
public class HttpNettyServer {



    public void openServer(int port){

        ServerBootstrap  bootstrap =new ServerBootstrap();

        bootstrap.channel(NioServerSocketChannel.class);

        EventLoopGroup base=new NioEventLoopGroup(1) ;
        EventLoopGroup work=new NioEventLoopGroup(8) ;
        bootstrap.group(base,work);

        bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {

                ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
                ch.pipeline().addLast("http",new HttpObjectAggregator(65536));
                ch.pipeline().addLast("http-response",new HttpResponseEncoder());
                ch.pipeline().addLast("http-servlet",new HttpServletHandler() );
            }
        });

        try {
            ChannelFuture future= bootstrap.bind(port).sync();
            System.out.println("netty start"+port);
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private  static class HttpServletHandler extends SimpleChannelInboundHandler{

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {

            if(o instanceof LastHttpContent){

                FullHttpResponse response =new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/html;charset=UTF-8");
                response.content().writeBytes("hello sun yi ge".getBytes());
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            }


        }
    }

    public static void main(String[] args) {
        new HttpNettyServer().openServer(8081);
    }
}
